﻿using Microsoft.AspNetCore.Mvc;
using NewsMVC.Models.Database;
using System.Linq;

namespace NewsMVC.Controllers
{
    public class NewsController : Controller
    {
        //定义数据库上下文
        private readonly NewsContext _db;

        public NewsController(NewsContext db)
        {
            _db = db;
        }


        [Route("/")]
        [Route("/index.html")]
        //name = cId 默认为0代表全部，>0代表需要查询的分类
        public IActionResult Index(int cid = 0)
        {
            //1.数据库查询数据
            //上下文.表名
            var list = _db.Categories.ToList();

            var news = _db.News.ToList();

            //取分类ID跳转分类新闻
            if (cid > 0)
            {
                //将筛选后的数据赋值给news
                news = news.Where(x => x.CateId == cid).ToList();
            }

            //2.把数据从控制器方法传递到页面
            ViewData["category"] = list;
            ViewData["news"] = news;

            return View();
        }

        [Route("/Detail.html")]
        public IActionResult Detail(int id)
        {
            //查询单条的数据
            var New = _db.News.FirstOrDefault(x => x.NewsId == id);
            ViewData["New"] = New;
            
            var list=_db.Categories.ToList();
            ViewData["category"] = list;

            return View();
        }
    }
}
